/**
 * Created by zhouli on 18/2/7
 * Email li.zhou@huilianyi.com
 * //扩展字段组件需要被复用，成本中心扩展字段也需要用
 //凡是需要用到扩展字段配置的地方
 */
import React from 'react';
import {connect} from 'react-redux';
import {
  Button,
  Icon, Input,
  Modal,
  Switch
} from 'antd';
import 'styles/components/template/extend-field-setting/extend-field.scss';
import {deepCopy} from 'share/common';
import {ListSort} from 'components/index';
import WidgetSetting from 'components/template/widget/widget-setting';
import {messages} from "share/common";

let customFormFieldsSorted = [];

class ExtendFieldComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      data: [],
      filedMax: 10,
      customFromOriginList: [],//可以选择表单类型
      customFromOriginListWithOften: [],//可以选择表单类型,常用类型
      customFrom: {},//配置的表单
    }
  }

  componentWillMount() {
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      loading: nextProps.loading,
      filedMax: nextProps.filedMax,
      customFrom: nextProps.customFrom,
      customFromOriginList: nextProps.customFromOriginList,
      customFromOriginListWithOften: nextProps.customFromOriginListWithOften,
    })
  }

  componentDidMount() {
  }

  //添加字段
  addFieldItem = (field) => {
    console.log(field)
    let item = deepCopy(field);
    let customFrom = this.state.customFrom;
    item.sequence = customFrom.customFormFields.length;
    if (item.sequence >= this.state.filedMax) {
      Modal.warning({
        title: messages('components.key464'/*提示*/),
        content: messages('components.key465'/*最多只能添加*/) + this.state.filedMax + messages('components.key466'/*个字段*/)
      });
      return;
    }
    customFrom.customFormFields.map((data) => {
      data._active = false;
    });
    item._active = true;
    item.sequence = customFrom.customFormFields.length > 0 ? customFrom.customFormFields.length : 0;
    // 把模板的多语言设置到表单
    item.fieldNameI18n = item.i18n.name;
    item.promptInfoI18n = item.i18n.promptInfo;
    customFrom.customFormFields.push(item);
    this.setState({
      customFrom,
      loading: false
    })
  }

  //激活表单字段
  activeFieldItem = (e, item) => {
    e.stopPropagation();
    let customFrom = this.state.customFrom;
    customFrom.customFormFields.map((data) => {
      data._active = false;
    })
    item._active = true;
    this.setState({
      customFrom,
      loading: false
    })
  }

  disabledFieldItem = (e, item) => {
    // valid
    console.log(e)
    console.log(item)
    item.valid = e;
    let customFrom = this.state.customFrom;
    this.setState({
      customFrom,
    })
  }
  /*
  * @departed
  * 移除表单字段
  * 需求6399 不要删除，改为禁用
  * 与产品确认过了：只能创建10个，且一旦创建错误，能用的就少一个
  * */
  removeFieldItem = (e, item) => {
    e.stopPropagation();
    let customFrom = this.state.customFrom;
    //移除表单字段
    customFrom.customFormFields.map((data, index) => {
      if (data.sequence === item.sequence) {
        customFrom.customFormFields.splice(index, 1);
      }
    })
    //重新排序
    customFrom.customFormFields.map((data, index) => {
      data.sequence = index;
    })
    //如果删除是激活的，立即设置一个
    if (item._active && customFrom.customFormFields.length > 0) {
      customFrom.customFormFields[0]._active = true;
    }
    setTimeout(() => {
      this.setState({
        customFrom,
        loading: false
      })
      // todo
      // > 800ms 才行
      // 不然删除一个后，就无法拖拽了
    }, 800)
  }

  //排序结果
  handleSortFieldItem = (result) => {
    customFormFieldsSorted = result;
  };

  getDefaultEnumerationDataSource = (field) => {
    let customFromOriginListWithOften = this.props.customFromOriginListWithOften;
    let dataSource = '';
    customFromOriginListWithOften.map(item => {
      if (field.defaultValue === item.defaultValue) {
        dataSource = item.dataSource;
      }
    });
    return dataSource;
  }
  //校验字段
  validete = () => {
    //保存之前，把数据处理好，验证好
    let customFrom = this.state.customFrom;
    let fields = customFrom.customFormFields;
    for (let i = 0; i < fields.length; i++) {
      let field = fields[i];
      if (field.fieldName === '' || field.fieldName === null || !field.fieldName) {
        //fieldName不能为空
        Modal.warning({
          title: messages('components.key464'/*提示*/),
          content: messages('components.key467'/*字段名称不能为空*/)
        });
        return false;
      }
      if (field.messageKey === 'cust_list') {
        if (field.fieldCode === 'heliosspc_remark_control' && !field.fieldOID) {
          let dataSource = this.getDefaultEnumerationDataSource(field);
          field.dataSource = dataSource;
        }
        if (!field.dataSource) {
          Modal.warning({
            title: messages('components.key464'/*提示*/),
            content: messages('components.key468'/*选择列表不能为空*/)
          });
          return false;
        }
        let dataSource = JSON.parse(field.dataSource);
        if (!dataSource.customEnumerationOID) {
          Modal.warning({
            title: messages('components.key464'/*提示*/),
            content: messages('components.key468'/*选择列表不能为空*/)
          });
          return false;
        }
      }
    }
    return true;
  }

  cancel = () => {
    this.props.cancel()
  }
  /**
   * 根据拖拽排序的结果，排序表单字段
   * @param originFields  最初的字段顺序
   * @param sortedFields  被拖拽后的顺序字段
   * @return field 排序好的字段
   */
  _getCustomFormFieldsBySortRes = (originFields, sortedFields) => {
    if (originFields.length > 0) {
      if (sortedFields.length > 0) {
        let arr = [];
        if (originFields.length > sortedFields.length) {
          //先拖拽过，添加字段后，就没有拖拽过
          sortedFields.map((item, index) => {
            let i = parseInt(item["key"]);
            originFields[i].sequence = index;
            arr[index] = originFields[i];
          })
          for (let n = sortedFields.length; n < originFields.length; n++) {
            arr[n] = originFields[n];
          }
          return arr;
        } else {
          //拖拽过
          sortedFields.map((item, index) => {
            let i = parseInt(item["key"]);
            originFields[i].sequence = index;
            arr[index] = originFields[i];
          })
          return arr;
        }
      } else {
        //没有拖拽过
        return originFields;
      }
    } else {
      //没有字段了
      return [];
    }
  }
  //保存配置好的表单
  saveFrom = () => {
    if (this.validete()) {
      let customFrom = deepCopy(this.state.customFrom);
      let customFormFields = deepCopy(this.state.customFrom.customFormFields);
      let customFormFieldsNew = this._getCustomFormFieldsBySortRes(customFormFields, customFormFieldsSorted);
      customFrom.customFormFields = customFormFieldsNew;
      this.props.saveFrom(customFrom)
    }
  }
  back = () => {
    this.context.router.goBack();
  }
  handleChangeField = (field) => {
    let customFrom = this.state.customFrom;
    for (let i = 0; i < customFrom.customFormFields.length; i++) {
      let data = customFrom.customFormFields[i];
      if (field.sequence === data.sequence) {
        customFrom.customFormFields[i] = field;
        customFrom.customFormFields[i].i18n.promptInfo = field.promptInfoI18n;
        customFrom.customFormFields[i].i18n.fieldName = field.fieldNameI18n;
      }
    }
    this.setState({
      customFrom: customFrom,
      loading: false
    })
  }
  getfieldDesc = (messageKey, list) => {
    let desc = "";
    list.map((data) => {
      if (data.messageKey === messageKey) {
        desc = data.description;
      }
    })
    return desc;
  }
  //渲染 激活的表单字段  详情
  renderFiledItemDetail = () => {
    let customFrom = this.state.customFrom;
    let customFromOriginList = this.state.customFromOriginList;
    let customFromOriginListWithOften = this.state.customFromOriginListWithOften;
    let item = {};
    if (customFrom.customFormFields && customFrom.customFormFields.length > 0) {
      customFrom.customFormFields.map((data) => {
        if (data._active) {
          item = data;
          item.messageKeyDesc = this.getfieldDesc(item.messageKey, customFromOriginListWithOften);
        }
      })
      return (
        <div>
          <WidgetSetting widget={item}
                         disabled={(item.fieldCode && item.fieldCode.split() &&
                           item.fieldCode.split("_")[0] === "heliosspc")}
                         valueListDisabled={item.id}
                         fieldRequiredDisabled={false}
                         showFieldCode={true}
                         isExtendField={true}
                         showConfig={{
                           isReadOnly: false,
                           isPDFShow: false,
                           required: true
                         }}
                         valueKey={"sequence"}
                         needType
                         widgetList={customFromOriginList.concat(customFromOriginListWithOften)}
                         onChange={this.handleChangeField}/>
        </div>
      )
    } else {
      return (<div/>)
    }
  }
  //渲染表单
  renderFiledItem = () => {
    let form = this.state.customFrom;
    let fields = form.customFormFields ? form.customFormFields : [];
    if (fields.length > 0) {
      let dragList = fields.map((item, index) => {
        let className = 'field-item';
        if (item._active) {
          className = 'field-item field-item-active';
        } else {
          className = 'field-item';
        }
        let closeIcon = null;
        if (this.props.leftDragable) {
          closeIcon = <div className="f-right close-btn">
              <Switch onChange={(e) => {
                this.disabledFieldItem(e, item)
              }}
                    checked={item.valid}
                    checkedChildren={<Icon type="check"/>}
                    unCheckedChildren={<Icon type="cross"/>}/>

          </div>;
        } else {
          closeIcon = <div/>;
        }
        return (
          <div className={className}
               key={item.sequence}
               origin={item}
               onClick={(e) => {
                 this.activeFieldItem(e, item)
               }}
          >
            <div className="f-left">
              <div className="f-left left-field-item-index">
                <span>{messages('components.key998')/*系统序号*/}</span>
                <span>{item.systemSequence}</span>
              </div>
              <div className="f-left left-field-item-title">{item.fieldName}</div>
              <div className="f-left left-field-item-inp">{item.promptInfo}</div>
              <div className="clear"/>
            </div>
            {closeIcon}
            <div className="clear"/>
          </div>
        )
      })

      if (this.props.leftDragable) {
        return (
          <div className="list-drag-wrap">
            <div className="list-drag-inner-wrap">
              <ListSort
                onChange={this.handleSortFieldItem}
                dragClassName="list-drag-selected"
              >
                {dragList}
              </ListSort>
            </div>
          </div>
        )
      } else {
        return (
          <div className="list-drag-wrap">
            <div className="list-drag-inner-wrap">
              <div>
                {dragList}
              </div>
            </div>
          </div>
        )
      }
    } else {
      return (<div/>)
    }
  }
  //渲染表单列表：右边的列表
  renderFiledList = () => {
    let list = this.state.customFromOriginList;
    if (list.length > 0) {
      return list.map((item) => {
        return (
          <div className="field-list-item"
               onClick={() => {
                 this.addFieldItem(item)
               }}
               type={item.messageKey}
               key={item.guiWidgetOID}
          >
            {item.name}
          </div>
        )
      })
    } else {
      return (<div/>)
    }
  }
  //渲染表单列表：右边的列表,常用扩展字段类型
  renderFiledListWithOften = () => {
    let list = this.state.customFromOriginListWithOften;
    if (list.length > 0) {
      return list.map((item) => {
        return (
          <div className="field-list-item"
               onClick={() => {
                 this.addFieldItem(item)
               }}
               type={item.messageKey}
               key={item.guiWidgetOID}
          >
            {item.name}
          </div>
        )
      })
    } else {
      return (<div/>)
    }
  }

  renderRightContent = (rightIsShow, showOftenField) => {
    if (rightIsShow) {
      return (
        <div className="extend-field-content-right f-left">
          <div className="field-list">
            <div className="extend-field-title">
              {messages('components.key469'/*点击添加字段类型*/)}
            </div>
            {/*右边的列表*/}
            {this.renderFiledList()}
            <div className="clear"/>
          </div>
          {showOftenField && <div className="field-list">
            <div className="extend-field-title"> {messages('components.key470'/*常用扩展字段*/)}
            </div>
            {/*右边的列表*/}
            {this.renderFiledListWithOften()}
            <div className="clear"/>
          </div>}

          <div className="field-active">
            {this.renderFiledItemDetail()}
          </div>
        </div>
      )
    } else {
      return <div/>
    }
  }
  renderBottomBtn = (bottomBtnIsShow, loading) => {
    if (bottomBtnIsShow) {
      return (
        <div className="extend-field-btn-wrap">
          <Button type="primary" loading={loading} onClick={this.saveFrom}>
            {messages("common.save") /*保存*/}
          </Button>&nbsp;&nbsp;&nbsp;
          <Button onClick={this.cancel}>
            {messages("common.back") /*返回*/}
          </Button>
        </div>
      )
    } else {
      return <div/>
    }
  }

  //获取扩展字段表单
  render() {
    const {filedMax, loading} = this.state;
    const {header, footer, bottomBtnIsShow, rightIsShow, showOftenField} = this.props;
    return (
      <div className="extend-field-wrap-component">
        <div>
          {header}
        </div>
        <div className="extend-field-content">
          <div className="extend-field-content-left f-left">
            <div className="extend-field-title">
              {messages('components.key465'/*最多只能添加*/) + filedMax + messages('components.key466'/*个字段*/)}
            </div>
            {/*左边的可以拖拽区*/}
            {this.renderFiledItem()}
          </div>
          {this.renderRightContent(rightIsShow, showOftenField)}
          <div className="clear"/>
        </div>
        {this.renderBottomBtn(bottomBtnIsShow, loading)}
        <div>
          {footer}
        </div>
      </div>
    )
  }
}

// 这个组件可以被导入其他地方可以配置
ExtendFieldComponent.propTypes = {
  header: React.PropTypes.node,//
  footer: React.PropTypes.node,//
  filedMax: React.PropTypes.number,//可以配置的字段数目
  customFrom: React.PropTypes.object,//
  customFromOriginList: React.PropTypes.array,//
  customFromOriginListWithOften: React.PropTypes.array,//
  saveFrom: React.PropTypes.func,//
  cancel: React.PropTypes.func,//
  rightIsShow: React.PropTypes.bool,//右边部分是否显示
  bottomBtnIsShow: React.PropTypes.bool,//下边的按钮是否显示
  leftDragable: React.PropTypes.bool,//左边部分是否可以拖拽
  showOftenField: React.PropTypes.bool,//是否展示常用扩展字段
};
ExtendFieldComponent.defaultProps = {
  filedMax: 10,
  loading: false,
  bottomBtnIsShow: true,
  leftDragable: true,
  rightIsShow: true,
  showOftenField: false,
  customFromOriginListWithOften: [],
};
ExtendFieldComponent.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
  }
}

export default connect(mapStateToProps)(ExtendFieldComponent);


